<template>
  <span class="region__select">
    <el-input v-model="regionDetails" disabled placeholder="请选择地区">
      <template slot="append">
        <el-button @click="showRegionSelect"><i class="el-icon-s-promotion" /></el-button>
      </template>
    </el-input>
    <model-dialog
      :visible="dialogVisible"
      :show-close="false"
      custom-class="region__select_dialog"
      title="地区选择器"
      width="680px"
      @close="dialogVisible=!dialogVisible">
      <div class="dialog__container">
        <el-form :model="regionInfo" label-width="80px">
          <el-form-item label="第一级:">
            <el-row>
              <el-col :span="11">
                <el-select v-model="regionInfo.provinceId" :disabled="disableProvince || disableCity" filterable @change="handlerChange(1)">
                  <el-option :key="'0'" :value="'0'" :label="'请选择省'" />
                  <el-option v-for="item in provinces" :key="item.id" :value="item.id" :label="item.name+'('+item.adCode+')'" />
                </el-select>
              </el-col>
              <el-col :span="13">
                <div class="tip">请根据实际情况选择,一般为省、直辖市</div>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="第二级:">
            <el-row>
              <el-col :span="11">
                <el-select v-model="regionInfo.cityId" :disabled="disableCity" filterable @change="handlerChange(2)">
                  <el-option :key="'0'" :value="'0'" :label="'请选择市'" />
                  <el-option v-for="item in citys" :key="item.id" :value="item.id" :label="item.name+'('+item.adCode+')'" />
                </el-select>
              </el-col>
              <el-col :span="13">
                <div class="tip">一般为地级市州，直辖市、直管县时为区县</div>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="第三级:">
            <el-row>
              <el-col :span="11">
                <el-select v-model="regionInfo.areaId" filterable @change="handlerChange(3)">
                  <el-option :key="'0'" :value="'0'" :label="'请选择区县'" />
                  <el-option v-for="item in areas" :key="item.id" :value="item.id" :label="item.name+'('+item.adCode+')'" />
                </el-select>
              </el-col>
              <el-col :span="13">
                <div class="tip">一般为区县，直辖市、直管县时为乡镇街道</div>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item v-if="!hideStreet" label="第四级:">
            <el-row>
              <el-col :span="11">
                <el-select v-model="regionInfo.streetId" filterable @change="handlerChange(4)">
                  <el-option :key="'0'" :value="'0'" :label="'请选择街道'" />
                  <el-option v-for="item in streets" :key="item.id" :value="item.id" :label="item.name+'('+item.adCode+')'" />
                </el-select>
              </el-col>
              <el-col :span="13">
                <div class="tip">乡镇、街道</div>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </div>
      <template slot="footer">
        <el-button type="primary" @click="getSelected()">确 定</el-button>
      </template>
    </model-dialog>
  </span>
</template>

<script>
export default {
  name: 'RegionSelector',
  props: {
    value: { type: String, default: '' },
    hideStreet: { type: Boolean, default: false }, // 隐藏街道
    requiredStreet: { type: Boolean, default: true }, // 是否必填
    disableProvince: { type: Boolean, default: false }, // 市不可选
    disableCity: { type: Boolean, default: false } // 市不可选
  },
  data() {
    return {
      regionDetails: '',
      dialogVisible: false,
      provinces: [],
      citys: [],
      areas: [],
      streets: [],
      /**
       * 根据v-model传递得值，进行解析获得
       */
      analysisRegion: {
        provinceId: '0',
        cityId: '0',
        areaId: '0',
        streetId: '0'
      },
      /**
       * 为了监听值发生变化，而定义得值
       */
      regionInfo: {
        provinceId: '0',
        cityId: '0',
        areaId: '0',
        streetId: '0'
      },
      extRegionInfo: {
        provinceSelected: { id: '', name: '' },
        citySelected: { id: '', name: '' },
        areasSelected: { id: '', name: '' },
        streetsSelected: { id: '', name: '' }
      },
      selectedInfo: {}
    }
  },
  watch: {
    'regionInfo.provinceId': function(val, oldVal) {
      if (val !== '0') {
        this.getCity()
        this.$emit('provinceChange', this.regionInfo)
      } else {
        this.citys = []
        this.regionInfo.cityId = '0'
        this.regionInfo.areaId = '0'
        this.regionInfo.streetId = '0'
      }
    },
    'regionInfo.cityId': function(val, oldVal) {
      if (val !== '0') {
        this.getArea()
      } else {
        this.areas = []
        this.regionInfo.areaId = '0'
        this.regionInfo.streetId = '0'
      }
    },
    'regionInfo.areaId': function(val, oldVal) {
      if (val !== '0') {
        this.getStreet()
      } else {
        this.streets = []
        this.regionInfo.streetId = '0'

        this.extRegionInfo.areasSelected.name = ''
        this.extRegionInfo.areasSelected.id = ''
      }
    },
    'regionInfo.streetId': function(val) {
      const $this = this
      if (val === '0') {
        $this.extRegionInfo.streetsSelected.name = ''
        $this.extRegionInfo.streetsSelected.id = ''
      }
    },
    value: function(val) {
      this.analysisRegionResult(this.value)
    }
  },
  created: function() {
    this.analysisRegionResult(this.value)
  },
  methods: {
    analysisRegionResult(val) {
      if (val) {
        this.regionDetails = this.common.regionFormat(val)
        /**
         *  area: "371402000000"
            city: "371400000000"
            province: "370000000000"
            street: "371402001000"
         */
        var result = this.common.regionIdFormat(val)
        this.analysisRegion = {
          provinceId: result.province * 1,
          cityId: result.city * 1,
          areaId: result.area * 1,
          streetId: result.street ? result.street * 1 : '0'
        }
      } else {
        this.regionDetails = ''
        this.analysisRegion = {
          provinceId: '0',
          cityId: '0',
          areaId: '0',
          streetId: '0'
        }
      }
    },
    showRegionSelect() {
      this.analysisRegionResult(this.value)
      this.dialogVisible = true
      this.getProvince()
      setTimeout(() => {
        this.regionInfo.provinceId = (this.analysisRegion.provinceId === 0 ? '0' : this.analysisRegion.provinceId)
        this.regionInfo.cityId = (this.analysisRegion.cityId === 0 ? '0' : this.analysisRegion.cityId)
        this.regionInfo.areaId = (this.analysisRegion.areaId === 0 ? '0' : this.analysisRegion.areaId)
        this.regionInfo.streetId = (this.analysisRegion.areaId === 0 ? '0' : this.analysisRegion.streetId)
      }, 200)
    },
    async handleSyncCacheRegion() {
      await this.$store.dispatch('syncCacheRegion')
      this.msgSuccess('缓存成功')
      this.getProvince()
    },

    // 省
    async getProvince() {
      const params = { id: 100000, loading: false }
      const response = await this.$store.dispatch('regionalLinkageCache', params)
      if (response.length === 0) {
        this.$alert('当前系统还未缓存地区，单击确定进行缓存！', '提示', {
          confirmButtonText: '确定',
          showClose: false,
          callback: action => {
            this.handleSyncCacheRegion()
          }
        })
      }
      this.provinces = [...response]
    },
    // 市
    async getCity() {
      const params = { id: this.regionInfo.provinceId, loading: false }
      const response = await this.$store.dispatch('regionalLinkageCache', params)
      this.citys = [...response]
    },
    // 县
    async getArea() {
      const params = { id: this.regionInfo.cityId, loading: false }
      const response = await this.$store.dispatch('regionalLinkageCache', params)
      this.areas = [...response]
    },
    // 街道
    async getStreet() {
      const params = { id: this.regionInfo.areaId, loading: false }
      const response = await this.$store.dispatch('regionalLinkageCache', params)
      this.streets = [...response]
    },
    setSelected() {
      this.selectedInfo = {}
      const selectedIds = []
      const selectedRegionName = []
      const selectedRegionInfo1 = []
      const $this = this
      this.provinces.forEach(item => {
        if (item.id === this.regionInfo.provinceId) {
          $this.extRegionInfo.provinceSelected.name = item.name
          $this.extRegionInfo.provinceSelected.id = item.id
          selectedIds.push(item.id)
          selectedRegionName.push(item.name)
          selectedRegionInfo1.push(item.id + ':' + item.name)
        }
      })
      this.citys.forEach(item => {
        if (item.id === this.regionInfo.cityId) {
          $this.extRegionInfo.citySelected.name = item.name
          $this.extRegionInfo.citySelected.id = item.id
          selectedIds.push(item.id)
          selectedRegionName.push(item.name)
          selectedRegionInfo1.push(item.id + ':' + item.name)
        }
      })
      this.areas.forEach(item => {
        if (item.id === this.regionInfo.areaId) {
          $this.extRegionInfo.areasSelected.name = item.name
          $this.extRegionInfo.areasSelected.id = item.id
          selectedIds.push(item.id)
          selectedRegionName.push(item.name)
          selectedRegionInfo1.push(item.id + ':' + item.name)
        }
      })
      this.streets.forEach(item => {
        if (item.id === this.regionInfo.streetId) {
          $this.extRegionInfo.streetsSelected.name = item.name
          $this.extRegionInfo.streetsSelected.id = item.id
          selectedIds.push(item.id)
          selectedRegionName.push(item.name)
          selectedRegionInfo1.push(item.id + ':' + item.name)
        }
      })
      if (selectedIds.length === 3) {
        // selectedIds.push('-1')
        // selectedRegionName.push('-1')
        // selectedRegionInfo1.push('-1:-1')
      }
      this.selectedInfo.selectedIds = selectedIds.join(',')
      this.selectedInfo.selectedRegion = selectedRegionName.join('')
      this.selectedInfo.selectedRegionInfo1 = selectedRegionInfo1.join(';')
    },
    getSelected() {
      this.setSelected()
      this.selectedInfo.regionInfo = this.regionInfo
      this.selectedInfo.extRegionInfo = this.extRegionInfo
      if (this.regionInfo.provinceId * 1 === 0 ||
                this.regionInfo.cityId * 1 === 0 ||
                this.regionInfo.areaId * 1 === 0 ||
                (this.requiredStreet && !this.hideStreet && this.regionInfo.streetId * 1 === 0 && this.streets.length > 0)) {
        this.showMessage('请选择地区')
      } else {
        this.showErr = false
        this.dialogVisible = false
        this.regionDetails = this.selectedInfo.selectedRegion
        this.$emit('input', this.selectedInfo.selectedRegionInfo1)
        this.$emit('selected', this.selectedInfo)
      }
    },

    showMessage(msg) {
      this.$message({
        showClose: true,
        message: msg,
        type: 'warning'
      })
    },
    handlerChange(level) {
      if (level === 1) {
        this.regionInfo.cityId = '0'
        this.regionInfo.areaId = '0'
        this.regionInfo.streetId = '0'
      }
      if (level === 2) {
        this.regionInfo.areaId = '0'
        this.regionInfo.streetId = '0'
      }
      if (level === 3) {
        this.regionInfo.streetId = '0'
      }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.el-dialog__body{
    padding: 5px 20px
 }
.region__select_dialog{

    .dialog__container{
        .tip{
            font-size: 12px;
        }
        .el-form-item{
            margin-bottom: 5px
        }
        .el-select{
            width: 95%
        }
        .el-textarea{
            width: 95%
        }
        }
}
</style>
